package com.example.gyj.service;

import com.example.gyj.dao.UserDao;
import com.example.gyj.entity.User;
import com.example.gyj.exception.GlobalException;
import com.example.gyj.redis.UserKey;
import com.example.gyj.result.CodeMsg;
import com.example.gyj.util.Md5Util;
import com.example.gyj.util.UUIDUtil;
import com.example.gyj.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Gao
 * @date 2018/10/20
 */
@Service
public class LoginService {

    public static final String COOKIE_NAME_TOKEN = "token";

    @Autowired
    private UserDao userDao;

    @Autowired
    private RedisService redisService;

    public String login(HttpServletResponse response, LoginVo loginvo) {
        if (loginvo == null) {
            throw new GlobalException(CodeMsg.SERVER_ERROR);
        }
        String mobile = loginvo.getMobile();
        String fromPass = loginvo.getPassword();
        //判断手机号是否存在
        User user = userDao.getUserById(Long.valueOf(mobile));
        if (user == null) {
            //手机号不存在异常
            throw new GlobalException(CodeMsg.MOBILE_NOT_EXIST);
        }
        //验证密码
        String dbPass = user.getPassword();
        String saltDB = user.getSalt();
        String calcPass = Md5Util.fromPassToDBPass(fromPass, saltDB);
        if (!calcPass.equals(dbPass)) {
            //密码错误
            throw new GlobalException(CodeMsg.PASSWORD_ERROR);
        }
        String token = UUIDUtil.uuid();
        addCookie(response, token, user);

        return token;
    }

    public void addCookie(HttpServletResponse response, String token, User user) {
        redisService.set(UserKey.token, token, user);
        Cookie cookie = new Cookie(COOKIE_NAME_TOKEN, token);
        //设置cookie有效期
        cookie.setMaxAge(UserKey.token.expireSeconds());
        cookie.setPath("/");
        //将cookie写到response中
        response.addCookie(cookie);
    }
}
